package com.wing.user.service;

import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import com.wing.common.constant.GlobalConstants;
import com.wing.common.constant.SapUtils;
import com.wing.common.constant.SecurityConstants;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.LocalDateTimeUtils;
import com.wing.common.utils.RSAUtils;
import com.wing.common.utils.Result;
import com.wing.oauth2.feign.LoginFeignClient;
import com.wing.user.dao.RoleDao;
import com.wing.user.dao.SystemDingTalkInfoDao;
import com.wing.user.dao.UserDao;
import com.wing.user.model.entity.*;
import com.wing.user.model.response.EnterpriseInfoVO;
import com.wing.user.model.response.SysPhoneCodeVo;
import com.wing.user.model.response.UserAuthVO;
import com.wing.user.model.response.UserVO;
import com.wing.user.utils.DingDingUtils;
import com.wing.user.utils.ReportUtil;
import com.wing.web.excel.UserExcelIn;
import com.wing.web.excel.UserInfoExcelIn;
import com.wing.web.utils.JwtUtils;
import com.wing.wecom.service.ContactUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 系统用户-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {

    @Autowired
    private ContactUserService contactUserService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private CompanyInfoService companyInfoService;
    @Autowired
    private FaceRecognitionService faceRecognitionService;
    @Value("${domain.name}")
    private String domainName;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Value("${platform.gatewayUrl}")
    private String gatewayUrl;

    @Autowired
    private RoleMenuService roleMenuService;

    @Autowired
    private LoginFeignClient loginFeignClient;

    @Resource
    PositionService positionService;

    @Override
    public UserAuthVO getByUsername(String username) {
        UserAuthVO userAuthVO = baseMapper.getByUsername(username);
//        if (userAuthVO.getUserType() == 2) {
//            //查询供应商信息比插入对象
//        }
        return userAuthVO;
    }

    @Override
    public UserAuthVO getByUserOrNickName(String username) {
        return baseMapper.getByUserOrNickName(username);
    }

    @Override
    public UserAuthVO getByPhone(String phone) {
        return baseMapper.getByPhone(phone);
    }

    @Override
    public UserAuthVO getByOpenId(String openId) {
        return baseMapper.getByOpenId(openId);
    }

    @Override
    @Transactional(readOnly = false)
    public JsonResult addUser(User user, String[] roleIds) {
        boolean result = false;
        //校验
        if (baseMapper.isExist(user.getUsername()) > 0) {
            throw new BusinessException(500, "员工工号已存在,添加失败!");
        }
        //检验身份证
        if (StringUtils.isNotBlank(user.getIdCard())) {
            QueryWrapper<User> qw = new QueryWrapper<>();
            qw.eq("id_card", user.getIdCard());
            User oldUser = baseMapper.selectOne(qw);
            if (oldUser != null) {
                throw new BusinessException(500, "身份证号已存在，请检查是否输入有误！");
            }
        }
        //检验ic卡号
        if (StringUtils.isNotBlank(user.getIcCard())) {
            User oldUser = baseMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getIcCard, user.getIcCard()));
            if (oldUser != null) {
                throw new BusinessException(500, "ic卡号已存在，请检查是否输入有误！");
            }
        }
        //检验手机号
        if (StringUtils.isNotBlank(user.getPhone())) {
            QueryWrapper<User> qwPhone = new QueryWrapper<>();
            qwPhone.eq("phone", user.getPhone());
            User oldUser = baseMapper.selectOne(qwPhone);
            if (oldUser != null) {
                throw new BusinessException(500, oldUser.getPhone() + "手机号已存在！");
            }
        }
        // 获取当前企业信息
        EnterpriseInfoVO enterpriseInfoVO = faceRecognitionService.getEnterpriseInfo();
        if (StringUtils.isEmpty(user.getEnterpriseCode())) {
            user.setEnterpriseCode(enterpriseInfoVO.getEnterpriseCode()); // 设置编码
        }
        user.setPassword(passwordEncoder.encode(DigestUtil.md5Hex("123456")));
        try {
            // 加密
            String passwordRsa = RSAUtils.encryptByPublicKey(RSAUtils.publicKey, DigestUtil.md5Hex("123456"));
            user.setPasswordRsa(passwordRsa);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (this.getBaseMapper().insert(user) > 0) {
            List<UserRole> userRoleList = new ArrayList<>();
            for (String roleId : roleIds) {
                UserRole userRole = new UserRole();
                userRole.setRoleId(Long.parseLong(roleId));
                QueryWrapper<User> nameQw = new QueryWrapper<>();
                nameQw.eq("username", user.getUsername());
                User userVo = baseMapper.selectOne(nameQw);
                userRole.setUserId(userVo.getId());
                userRoleList.add(userRole);
            }
            result = userRoleService.saveBatch(userRoleList);
        }
        if (result) {
            // 添加通用数据
            // 判断当前用户手机号是否已经存在
            int count = baseMapper.queryPhoneExists(user.getPhone());
            if (count > 0) {
//                throw new BusinessException(500, "手机号["+user.getPhone()+"]已存在，请联系以前的公司删除对应的人员数据");
            } else {
                baseMapper.addGeneralData(user.getPhone(), user.getEnterpriseCode());
            }


            // 企业微信对接
            // 创建企业微信成员
            /*ContactUserParam contactUserParam = new ContactUserParam();
            contactUserParam.setUserid(user.getId().toString()); // 成员UserID。对应管理端的帐号，企业内必须唯一。 使用人员ID代替
            contactUserParam.setName(user.getNickname()); // 成员名称
            contactUserParam.setAlias(null); // 成员别名
            contactUserParam.setMobile(user.getPhone()); // 手机号
            Department department = departmentService.getById(user.getDepartmentId()); // 获取人员部门
            Integer[] deptIdArr = {department.getQywxDeptId()};
            contactUserParam.setDepartment(deptIdArr); // 成员所属部门id列表
            contactUserParam.setOrder(null); // 部门内的排序值
            Role post = roleService.getById(user.getPostId());
            contactUserParam.setPosition(post.getName()); // 职务信息
            contactUserParam.setGender(user.getSex()); // 性别
            contactUserParam.setEmail(null); // 邮箱
            contactUserParam.setTelephone(null); // 座机
            contactUserParam.setLeaderInDept(null); // 个数必须和参数department的个数一致，表示在所在的部门内是否为部门负责人。1表示为部门负责人，0表示非部门负责人。在审批等应用里可以用来标识上级审批人
//            contactUserParam.setAvatarMediaid(domainName+"/file/admin/file/get/"+user.getHeaderImg()); // 成员头像的mediaid
            contactUserParam.setEnable(user.getIsJob().getValue() == 0 ? 1 : 0); // 启用/禁用成员。1表示启用成员，0表示禁用成员
            contactUserParam.setExtattr(null); // 自定义字段
            contactUserParam.setToInvite(true); // 是否邀请该成员使用企业微信（将通过微信服务通知或短信或邮件下发邀请，每天自动下发一次，最多持续3个工作日），默认值为true。
            contactUserParam.setExternalProfile(null); // 成员对外属性，字段详情见 对外属性
            contactUserParam.setExternalPosition(null); // 对外职务，如果设置了该值，则以此作为对外展示的职务，否则以position来展示。长度12个汉字内
            contactUserParam.setAddress(user.getAddress()); // 地址
            contactUserParam.setMainDepartment(null); // 主部门
            RespStatus respStatus = contactUserService.create(contactUserParam);
            if (!respStatus.success()) {
                if (respStatus.getErrcode() == 42001) { // access_token已过期
                    throw new BusinessException(300, "企业微信token过期");
                } else if (respStatus.getErrcode() == 60103) {
                    throw new BusinessException(300, "手机号码不合法");
                } else if (respStatus.getErrcode() == 60104) {
                    throw new BusinessException(300, "手机号码已存在");
                } else if (respStatus.getErrcode() == 40066) {
                    throw new BusinessException(300, "企业微信不存在该部门");
                } else {
                    throw new BusinessException(300, "创建企业微信成员失败");
                }
            }*/
//            // 腾讯人脸对接
//            if (StringUtils.isNotBlank(user.getHeaderImg())) {
//                // 是否创建人脸库
//                if (!enterpriseInfoVO.getIsCreateFaceDatabase()) {
//                    // 创建人员库
//                    JsonResult jsonResult = faceRecognitionService.createGroup(enterpriseInfoVO.getEnterpriseId(), enterpriseInfoVO.getEnterpriseName());
//                    if (JsonResult.Code.SUCCESS.getCode() != jsonResult.getCode()) {
//                        return jsonResult;
//                    }
//                    faceRecognitionService.updIsCreateFaceDatabase();
//                }
//                // 创建人员
//                JsonResult jsonResult = faceRecognitionService.CreatePerson(enterpriseInfoVO.getEnterpriseId(), user.getNickname(), user.getId().toString(), user.getHeaderImg());
//                return jsonResult;
//            }
        }
        return JsonResult.success();
    }

    @Override
    @Transactional(readOnly = false)
    public void addThirdUser(User user) {
        //用户名是否存在
        if (baseMapper.isExist(user.getUsername()) > 0) {
            throw new BusinessException(500, "用户名已存在");
        }
        //检验手机号
        if (StringUtils.isNotBlank(user.getPhone())) {
            QueryWrapper<User> qwPhone = new QueryWrapper<>();
            qwPhone.eq("phone", user.getPhone());
            User oldUser = baseMapper.selectOne(qwPhone);
            if (oldUser != null) {
                throw new BusinessException(500, oldUser.getPhone() + "手机号已存在！");
            }
        }
        user.setPassword(passwordEncoder.encode(DigestUtil.md5Hex("123456")));
        try {
            // 加密
            String passwordRsa = RSAUtils.encryptByPublicKey(RSAUtils.publicKey, DigestUtil.md5Hex("123456"));
            user.setPasswordRsa(passwordRsa);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (this.getBaseMapper().insert(user) > 0) {
            List<UserRole> userRoleList = new ArrayList<>();
            //获取角色信息
            QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
            roleQueryWrapper.eq("code", user.getUserRoleCode());
            Role role = roleService.getOne(roleQueryWrapper);
            if (role == null) {
                throw new BusinessException(500, "角色信息不存在");
            }
            //新增用户角色信息
            UserRole userRole = new UserRole();
            userRole.setRoleId(role.getId());
            userRole.setUserId(user.getId());
            userRoleService.save(userRole);
        }
    }

    @Override
    @Transactional(readOnly = false)
    public JsonResult update(User user, String[] roleIds) {
        User oldUser = baseMapper.selectById(user.getId());
        if (oldUser == null) {
            throw new BusinessException(300, "修改失败！");
        }

        //更新工号时判断工号是否存在
        if (!oldUser.getUsername().equals(user.getUsername()) &&
                baseMapper.isExist(user.getUsername()) > 0) {
            throw new BusinessException(300, "员工工号已存在，修改失败！");
        }
        //检验身份证
        if (StringUtils.isNotBlank(user.getIdCard())
                && !user.getIdCard().equals(oldUser.getIdCard())) {
            QueryWrapper<User> qw = new QueryWrapper<>();
            qw.eq("id_card", user.getIdCard());
            User isExist = baseMapper.selectOne(qw);
            if (isExist != null) {
                throw new BusinessException(500, "身份证号已存在，请检查是否输入有误！");
            }
        }
        //检验ic卡号
        if (StringUtils.isNotBlank(user.getIcCard()) && !user.getIcCard().equals(oldUser.getIcCard())) {
            User icUser = baseMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getIcCard, user.getIcCard()));
            if (icUser != null) {
                throw new BusinessException(500, "ic卡号已存在，请检查是否输入有误！");
            }
        }
        //检验手机号
        if (StringUtils.isNotBlank(user.getPhone())
                && !user.getPhone().equals(oldUser.getPhone())) {
            QueryWrapper<User> qwPhone = new QueryWrapper<>();
            qwPhone.eq("phone", user.getPhone());
            User userPhone = baseMapper.selectOne(qwPhone);
            if (userPhone != null) {
                throw new BusinessException(500, "手机号已存在！");
            }
        }

        int i = baseMapper.updateById(user);
        if (i > 0) {
            List<UserRole> userRoles = new ArrayList<>();
            for (String roleId : roleIds) {
                UserRole userRole = new UserRole();
                userRole.setRoleId(Long.parseLong(roleId));
                userRole.setUserId(user.getId());
                userRoles.add(userRole);
            }
            if (roleIds.length > 1 || !roleIds[0].equals("0")) {
                userRoleService.remove(new QueryWrapper<UserRole>().eq("user_id", user.getId()));
                if (!userRoleService.saveBatch(userRoles)) {
                    throw new BusinessException("修改失败");
                }
            }

            // 企业微信对接
            // 更新企业微信成员
            /*ContactUserParam contactUserParam = new ContactUserParam();
            contactUserParam.setUserid(user.getId().toString()); // 成员UserID。对应管理端的帐号，企业内必须唯一。 使用人员ID代替
            contactUserParam.setName(user.getNickname()); // 成员名称
            contactUserParam.setAlias(null); // 成员别名
            contactUserParam.setMobile(user.getPhone()); // 手机号
            Department department = departmentService.getById(user.getDepartmentId()); // 获取人员部门
            Integer[] deptIdArr = {department.getQywxDeptId()};
            contactUserParam.setDepartment(deptIdArr); // 成员所属部门id列表
            contactUserParam.setOrder(null); // 部门内的排序值
            Role post = roleService.getById(user.getPostId());
            contactUserParam.setPosition(post.getName()); // 职务信息
            contactUserParam.setGender(user.getSex()); // 性别
            contactUserParam.setEmail(null); // 邮箱
            contactUserParam.setTelephone(null); // 座机
            contactUserParam.setLeaderInDept(null); // 个数必须和参数department的个数一致，表示在所在的部门内是否为部门负责人。1表示为部门负责人，0表示非部门负责人。在审批等应用里可以用来标识上级审批人
            contactUserParam.setAvatarMediaid(user.getHeaderImg()); // 成员头像的mediaid
            contactUserParam.setEnable(user.getIsJob().getValue() == 0 ? 1 : 0); // 启用/禁用成员。1表示启用成员，0表示禁用成员
            contactUserParam.setExtattr(null); // 自定义字段
            contactUserParam.setExternalProfile(null); // 成员对外属性，字段详情见 对外属性
            contactUserParam.setExternalPosition(null); // 对外职务，如果设置了该值，则以此作为对外展示的职务，否则以position来展示。长度12个汉字内
            contactUserParam.setAddress(user.getAddress()); // 地址
            contactUserParam.setMainDepartment(null); // 主部门
            RespStatus respStatus = contactUserService.update(contactUserParam);
            if (!respStatus.success()) {
                if (respStatus.getErrcode() == 42001) { // access_token已过期
                    throw new BusinessException(300, "企业微信token过期");
                } else if (respStatus.getErrcode() == 60103) {
                    throw new BusinessException(300, "手机号码不合法");
                } else {
                    throw new BusinessException(300, "修改企业微信成员失败");
                }
            }*/
//            // 腾讯人脸对接
//            if (StringUtils.isNotBlank(user.getHeaderImg())) {
//                // 获取当前企业信息
//                EnterpriseInfoVO enterpriseInfoVO = faceRecognitionService.getEnterpriseInfo();
//                // 人员库删除人员
//                JsonResult deletePersonResult = faceRecognitionService.DeletePersonFromGroup(enterpriseInfoVO.getEnterpriseId(), user.getId().toString());
//                if (JsonResult.Code.SUCCESS.getCode() != deletePersonResult.getCode()) {
//                    return deletePersonResult;
//                }
//                // 创建人员
//                JsonResult jsonResult = faceRecognitionService.CreatePerson(enterpriseInfoVO.getEnterpriseId(), user.getNickname(), user.getId().toString(), user.getHeaderImg());
//                return jsonResult;
//            }
        }
        return JsonResult.success();
    }


    public JsonResult addUserHeader(User user) {
        User oldUser = baseMapper.selectById(user.getId());
        if (oldUser == null) {
            throw new BusinessException("未找到用户");
        }
        User userUpdate = new User();
        userUpdate.setId(user.getId());
        userUpdate.setHeaderImg(user.getHeaderImg());
        baseMapper.updateById(userUpdate);
//        // 腾讯人脸对接
//        if (StringUtils.isNotBlank(user.getHeaderImg())) {
//            // 获取当前企业信息
//            EnterpriseInfoVO enterpriseInfoVO = faceRecognitionService.getEnterpriseInfo();
//            if (!enterpriseInfoVO.getIsCreateFaceDatabase()) {
//                // 创建人员库
//                JsonResult createGroupResult = faceRecognitionService.createGroup(enterpriseInfoVO.getEnterpriseId(), enterpriseInfoVO.getEnterpriseName());
//                if (JsonResult.Code.SUCCESS.getCode() != createGroupResult.getCode()) {
//                    return createGroupResult;
//                }
//                faceRecognitionService.updIsCreateFaceDatabase();
//            }
//
//            // 人员库删除人员
//            JsonResult deletePersonResult = faceRecognitionService.DeletePersonFromGroup(enterpriseInfoVO.getEnterpriseId(), user.getId().toString());
//            if (JsonResult.Code.SUCCESS.getCode() != deletePersonResult.getCode()) {
//                return deletePersonResult;
//            }
//            // 创建人员
//            JsonResult jsonResult = faceRecognitionService.CreatePerson(enterpriseInfoVO.getEnterpriseId(), oldUser.getNickname(), user.getId().toString(), user.getHeaderImg());
//            return jsonResult;
//        }
        return JsonResult.success();
    }

    @Override
    public void addFaceData(User user) {
        User oldUser = baseMapper.selectById(JwtUtils.getLoginUserId());
        if (oldUser == null) {
            throw new BusinessException("未找到用户");
        }
        User userUpdate = new User();
        userUpdate.setId(oldUser.getId());
        userUpdate.setFaceData(user.getFaceData());
        userUpdate.setHeaderImg(user.getHeaderImg());
        baseMapper.updateById(userUpdate);
    }

    @Override
    public User getByUserId(Long id) {
        return baseMapper.getByUserId(id);
    }

    @Override
    public JSONObject findByUserId(Long userId, String clientId, String clientSecret, Long cacbId, String version, String enterpriseCode) {
        JSONObject json = new JSONObject();

        User user = baseMapper.selectById(userId);
        if (user == null) {
            throw new BusinessException(300, "用户不存在");
        }
        try {
            OkHttpClient client = new OkHttpClient();
            // 解密
            String password = RSAUtils.decryptByPrivateKey(RSAUtils.privateKey, user.getPasswordRsa());
            log.info("pwd:{}", password);
            String params = "?grant_type=password&scope=web&client_id=" + clientId + "&client_secret=" + clientSecret + "&username=" + user.getUsername()
                    + "&password=" + password + "&cabId=" + cacbId + "&version=" + version + "&enterpriseCode=" + enterpriseCode;
            String url = domainName + "/oauth2/admin/user/login" + params;
            Request request = new Request.Builder().header("Access-Control-Allow-Origin", "*")
                    .addHeader("dataType", "json")
                    .addHeader("contentType", "application/x-www-form-urlencoded")
                    .url(url)
                    .post(RequestBody.create(null, "")).build();
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                json = JSON.parseObject(response.body().string());
            } else {
                json.put("code", response.code());
                json.put("msg", response.message());
            }
        } catch (Exception e) {
//            e.printStackTrace();
            log.error("login fail", e);
            json.put("code", Result.Code.FAIL.getCode());
            json.put("msg", "登录失败");

        }
        return json;
    }

    @Override
    public JSONObject findByUserIcCard(String icCard, String clientId, String clientSecret, Long cabId, String version) {
        JSONObject json = new JSONObject();
        User user = baseMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getIcCard, icCard));
        if (user == null) {
            throw new BusinessException(300, "当前卡号未绑定用户");
        }
        try {
            OkHttpClient client = new OkHttpClient();
            // 解密
            String password = RSAUtils.decryptByPrivateKey(GlobalConstants.privateKey, user.getPasswordRsa());
            log.info("pwd:{}", password);
            String params = "?grant_type=password&scope=web&client_id=" + clientId + "&client_secret=" + clientSecret + "&username=" + user.getUsername()
                    + "&password=" + password + "&cabId=" + cabId + "&version=" + version;
            String url = domainName + "/oauth2/admin/user/login" + params;
            Request request = new Request.Builder().header("Access-Control-Allow-Origin", "*")
                    .addHeader("dataType", "json")
                    .addHeader("contentType", "application/x-www-form-urlencoded")
                    .url(url)
                    .post(RequestBody.create(null, "")).build();
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                json = JSON.parseObject(response.body().string());
            } else {
                json.put("code", response.code());
                json.put("msg", response.message());
            }
        } catch (Exception e) {
//            e.printStackTrace();
            log.error("login fail", e);
            json.put("code", Result.Code.FAIL.getCode());
            json.put("msg", "登录失败");

        }
        return json;
    }

    @Override
    public String applogin(String phone, String code, String codeKey) {
        return null;
    }

    @Override
    public UserVO getUserInfoByUserId(Long userId) {
        return baseMapper.getUserInfoByUserId(userId);
    }


    @Override
    @Transactional(readOnly = false)
    public JsonResult delete(Long userId) {
        User user = baseMapper.selectById(userId); // 获取当前删除的部门信息
        String headerImg = user.getHeaderImg(); // 头像
        String personId = user.getId().toString(); // 人员ID
        Department department = departmentService.getById(user.getDepartmentId());
        int i = baseMapper.deleteById(user);
        if (i > 0) {
            // 删除通用数据
            // 判断当前用户手机号通用数据是否已经存在
            SysPhoneCodeVo sysPhoneCodeVo = baseMapper.querySysPhoneCode(user.getPhone());
            if (null != sysPhoneCodeVo) {
                if (!sysPhoneCodeVo.getCode().equalsIgnoreCase(user.getEnterpriseCode())) {
                    throw new BusinessException(500, "数据错误");
                }
                if (baseMapper.delGeneralData(user.getPhone()) > 0) {
                    // redis移除对应数据

                }
                redisTemplate.delete(SecurityConstants.DS_PHONE_PREFIX + user.getPhone());
            }

            // 企业微信对接
            // 删除企业微信成员
            /*RespStatus respStatus = contactUserService.delete(personId);
            if(!respStatus.success()){
                if(respStatus.getErrcode() == 42001){ // access_token已过期
                    throw new BusinessException(300, "企业微信token过期");
                }else{
                    throw new BusinessException(300, "删除企业微信成员失败");
                }
            }*/

            // 腾讯人脸对接
            /**
             if (StringUtils.isNotBlank(headerImg)) {
             // 获取当前企业信息
             EnterpriseInfoVO enterpriseInfoVO = faceRecognitionService.getEnterpriseInfo();
             // 人员库删除人员
             faceRecognitionService.DeletePersonFromGroup(enterpriseInfoVO.getEnterpriseId(), personId);
             //                return jsonResult;
             }*/
        }
        return JsonResult.success();
    }

    @Override
    public void importExcel(List<UserExcelIn> list) {
        try {
            addExcel(list);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<UserExcelIn> exportList(Map paramsMap) {
        return baseMapper.exportList(paramsMap);
    }

    @Transactional(readOnly = false)
    void addExcel(List<UserExcelIn> list) {
        List<User> userList = this.list();
        List<User> resultList = new ArrayList<>();
        int i = 1;
        for (UserExcelIn item : list) {
            if (baseMapper.selectCount(new QueryWrapper<User>().eq("phone", item.getPhone())) > 0) {
                baseMapper.delete(new QueryWrapper<User>().eq("phone", item.getPhone()));
            }
            i++;
            if (StringUtils.isBlank(item.getCompanyInfoName())) {
                throw new BusinessException(300, "第" + i + "行企业未输入数据");
            }
            if (StringUtils.isBlank(item.getUsername())) {
                throw new BusinessException(300, "第" + i + "行用户名(工号)未输入数据");
            }
            if (StringUtils.isBlank(item.getNickname())) {
                throw new BusinessException(300, "第" + i + "行姓名未输入数据");
            }
            if (StringUtils.isBlank(item.getSex())) {
                throw new BusinessException(300, "第" + i + "行性别未选择数据");
            }
            if (StringUtils.isBlank(item.getDepartmentName())) {
                throw new BusinessException(300, "第" + i + "行部门未输入数据");
            }
            if (StringUtils.isBlank(item.getJobName())) {
                throw new BusinessException(300, "第" + i + "行岗位未输入数据");
            }
            if (StringUtils.isBlank(item.getPositionName())) {
                throw new BusinessException(300, "第" + i + "行职务未输入数据");
            }
            if (StringUtils.isBlank(item.getIdCard())) {
                throw new BusinessException(300, "第" + i + "行身份证号码未输入数据");
            }
            if (StringUtils.isBlank(item.getBirthday())) {
                throw new BusinessException(300, "第" + i + "行出生年月未输入数据");
            }
            if (StringUtils.isBlank(item.getAddress())) {
                throw new BusinessException(300, "第" + i + "行家庭住址未输入数据");
            }
            if (StringUtils.isBlank(item.getPhone())) {
                throw new BusinessException(300, "第" + i + "行联系电话未输入数据");
            }
            if (StringUtils.isBlank(item.getEntryTime())) {
                throw new BusinessException(300, "第" + i + "行入职时间未输入数据");
            }
            if (item.getPhone() != null && item.getPhone().contains("E")) {
                item.setPhone(item.getPhone().substring(0, item.getPhone().indexOf("E")) + "0");
            }
            User user = new User();
            Role roleFrom = new Role();
            // 获取企业
            CompanyInfo companyInfo = companyInfoService.getOne(new QueryWrapper<CompanyInfo>().eq("name", item.getCompanyInfoName()));
            if (companyInfo == null) {
                throw new BusinessException(300, "该企业数据不存在");
            }
            user.setCompanyInfoId(companyInfo.getId());
            //用户名
            user.setUsername(item.getUsername());
            //姓名
            user.setNickname(item.getNickname());
            //性别
            Integer sex = 1;
            if (StringUtils.isNotBlank(item.getSex()) && item.getSex().indexOf("男") == -1) {
                sex = 0;
            }
            user.setSex(sex);
            //部门
            QueryWrapper<Role> departmentQueryWrapper = new QueryWrapper<>();
            departmentQueryWrapper.eq("is_produce", 1);
            List<Role> departmentList = roleService.list(departmentQueryWrapper);
            Role department = departmentList.stream().filter(t -> t.getName().equals(item.getDepartmentName())).findFirst().orElse(null);
            if (department == null) {
                throw new BusinessException(300, "[" + item.getDepartmentName() + "]部门不存在");
            }
            user.setDepartmentId(department.getId());
            //岗位
            QueryWrapper<Role> jobQueryWrapper = new QueryWrapper<>();
            jobQueryWrapper.eq("is_produce", 0);
            List<Role> jobList = roleService.list(jobQueryWrapper);
            Role job = jobList.stream().filter(t -> t.getName().equals(item.getJobName())).findFirst().orElse(null);
            if (job == null) {
                throw new BusinessException(300, "[" + item.getJobName() + "]岗位不存在");
            }
            user.setPostId(job.getId());
            //职务
            QueryWrapper<Position> positionQueryWrapper = new QueryWrapper<>();
            List<Position> positionList = positionService.list(positionQueryWrapper);
            Position position = positionList.stream().filter(t -> t.getName().equals(item.getPositionName())).findFirst().orElse(null);
            if (position == null) {
                throw new BusinessException(300, "[" + item.getPositionName() + "]职务不存在");
            }
            user.setPositionId(position.getId());
            //学历
            user.setTeachInfo(item.getTeachInfo());
            //身份证号码
            user.setIdCard(item.getIdCard());
            //出生年月
            user.setBirthday(item.getBirthday());
            //家庭地址
            user.setAddress(item.getAddress());
            //联系电话
            user.setPhone(item.getPhone());
            //入职时间
            user.setEntryTime(item.getEntryTime());
            //养老保险
            user.setEndowmentInsurance(item.getEndowmentInsurance());
            //医疗保险
            user.setMedicalInsurance(item.getMedicalInsurance());
            //工伤保险
            user.setInjuryInsurance(item.getInjuryInsurance());
            //失业保险
            user.setJoblessInsurance(item.getJoblessInsurance());
            //衣服尺码
            user.setClothingCode(item.getClothingCode());
            //鞋子尺码
            user.setShoesCode(item.getShoesCode());
            //合同开始时间
            user.setContractStartTime(item.getContractStartTime());
            //合同结束时间
            user.setContractEndTime(item.getContractEndTime());
            // 获取当前企业信息
            EnterpriseInfoVO enterpriseInfoVO = faceRecognitionService.getEnterpriseInfo();
            if (StringUtils.isEmpty(user.getEnterpriseCode())) {
                user.setEnterpriseCode(enterpriseInfoVO.getEnterpriseCode()); // 设置编码
            }
            user.setPassword(passwordEncoder.encode(DigestUtil.md5Hex("123456")));
            try {
                String passwordRsa = RSAUtils.encryptByPublicKey(RSAUtils.publicKey, DigestUtil.md5Hex("123456"));
                user.setPasswordRsa(passwordRsa);
            } catch (Exception e) {
                e.printStackTrace();
            }
            User user1 = userList.stream().filter(t -> t.getUsername().equals(user.getUsername())).findFirst().orElse(null);
            if (user1 != null) {
                user.setId(user1.getId());
            }
            resultList.add(user);
        }
        this.saveOrUpdateBatch(resultList);
    }

    @Override
    public Page<User> pageList(Page<User> page, Map<String, Object> params) {
        List<User> list = baseMapper.list(page, params);
        page.setRecords(list);
        return page;
    }

    private int random() {
        StringBuilder str = new StringBuilder();//定义变长字符串
        Random random = new Random();
        //随机生成数字，并添加到字符串
        for (int i = 0; i < 8; i++) {
            str.append(random.nextInt(10));
        }
        //将字符串转换为数字并输出
        int num = Integer.parseInt(str.toString());
        return num;
    }

    /**
     * 同步东江用户数据
     */
    //@Scheduled(cron = "0 */5 * * * ?")
    @Transactional
    public void syncDjUserInfo() {
        System.out.println("执行-------");
        SapUtils httpUtil = new SapUtils();
        String resultText = httpUtil.execImpexpPaymentService();
        System.out.println("【测试---】接口结果>>>>result:{}:" + resultText);
        JSONArray jsonArray = JSON.parseArray(resultText);
        for (int i = 0; i < jsonArray.size(); i++) {
            User user = new User();
            JSONObject jsonObj = jsonArray.getJSONObject(i);
            String loginid = jsonObj.getString("loginid");
            String departmentname = jsonObj.getString("departmentname");
            String jobtitlename = jsonObj.getString("jobtitlename");
            Long departmentid = Long.valueOf(jsonObj.getString("departmentid"));
            String mobile = jsonObj.getString("mobile");
            Long userid = Long.valueOf(jsonObj.getString("id"));
            String lastname = jsonObj.getString("lastname");
            Integer status = Integer.valueOf(jsonObj.getString("status"));
            User oldUser = baseMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, loginid));
            // 获取当前企业信息
            EnterpriseInfoVO enterpriseInfoVO = faceRecognitionService.getEnterpriseInfo();
            //查询刀具柜系统用户的部门岗位
            UserVO userVO = baseMapper.getUserInfoByUserName(loginid);
            if (oldUser != null) {
                user.setThirdPartyDepartmentId(departmentid);
                user.setThirdPartyUserId(userid);
                oldUser.setNickname(lastname);
                oldUser.setUsername(loginid);
                oldUser.setPhone(mobile);
                oldUser.setStatus(status);
                //对比东江系统的部门数据，不同时就修改，取东江系统的部门
                Department department = new Department();
                if (!departmentname.equals(userVO.getDepartmentName())) {
                    department = departmentService.getOne(new LambdaQueryWrapper<Department>().eq(Department::getName, departmentname)
                            .eq(Department::getCompanyInfoId, enterpriseInfoVO.getEnterpriseId()));
                    if (department == null) {
                        throw new BusinessException(500, "同步失败,OA系统同步过来的部门名称为：" + departmentname + "--在刀具柜系统中不存在！请先添加");
                    } else {
                        oldUser.setDepartmentId(department.getId());
                    }
                }
                //对比东江系统的岗位数据，不同时就修改，取东江系统的岗位
                if (!jobtitlename.equals(userVO.getPostName())) {
                    Role serviceOne = roleService.getOne(new LambdaQueryWrapper<Role>().eq(Role::getName, jobtitlename)
                            .eq(Role::getCompanyInfoId, enterpriseInfoVO.getEnterpriseId()).eq(Role::getDepartmentId, department.getId()));
                    if (serviceOne == null) {
                        throw new BusinessException(500, "同步失败,OA系统同步过来的岗位名称为：" + jobtitlename + "--在刀具柜系统中部门名称为："
                                + department.getName() + "下不存在！请先添加");
                    } else {
                        oldUser.setPostId(serviceOne.getId());
                    }
                }
                baseMapper.updateById(oldUser);
            } else {
                user.setThirdPartyDepartmentId(departmentid);
                user.setThirdPartyUserId(userid);
                user.setNickname(lastname);
                user.setUsername(loginid);
                user.setPhone(mobile);
                user.setStatus(status);
                user.setCompanyInfoId(Long.valueOf(enterpriseInfoVO.getEnterpriseId()));
                //根据东江系统传过来的部门名称查询刀柜系统是否存在
                Department department2 = departmentService.getOne(new LambdaQueryWrapper<Department>().eq(Department::getName, departmentname)
                        .eq(Department::getCompanyInfoId, enterpriseInfoVO.getEnterpriseId()));
                if (department2 == null) {
                    throw new BusinessException(500, "同步失败,OA系统同步过来的部门名称为：" + departmentname + "--在刀具柜系统中不存在！请先添加");
                } else {
                    user.setDepartmentId(department2.getId());
                }

                //根据东江系统传过来的岗位名称查询刀柜系统是否存在
                Role serviceOne = roleService.getOne(new LambdaQueryWrapper<Role>().eq(Role::getName, jobtitlename)
                        .eq(Role::getCompanyInfoId, enterpriseInfoVO.getEnterpriseId()).eq(Role::getDepartmentId, department2.getId()));
                if (serviceOne == null) {
                    throw new BusinessException(500, "同步失败,OA系统同步过来的岗位名称为：" + jobtitlename + "--在刀具柜系统中部门名称为："
                            + department2.getName() + "下不存在！请先添加");
                } else {
                    user.setPostId(serviceOne.getId());
                }


                user.setEnterpriseCode(enterpriseInfoVO.getEnterpriseCode()); // 设置编码
                user.setPassword(passwordEncoder.encode(DigestUtil.md5Hex("123456")));
                try {
                    // 加密
                    String passwordRsa = RSAUtils.encryptByPublicKey(RSAUtils.publicKey, DigestUtil.md5Hex("123456"));
                    user.setPasswordRsa(passwordRsa);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                baseMapper.insert(user);
            }

        }
    }

    @Override
    public JsonResult costCenterBodyCount(String type, String startTime, String endTime, String param, Long enterpriseId, String costCenter) {
        HashMap hm = new HashMap();
        hm.put("title", "按成本中心统计人数");

        List list = new ArrayList();

        if (StringUtils.isNotBlank(type)) {

            if (type.equals("0")) { // 日
                list.addAll(baseMapper.costCenterBodyCount(ReportUtil.dayUtil().get(0), ReportUtil.dayUtil().get(1), param, enterpriseId, costCenter));
                hm.put("totalSum", baseMapper.costCenterBodyCountTotal(enterpriseId));

            } else if (type.equals("1")) { // 周
                list.addAll(baseMapper.costCenterBodyCount(ReportUtil.weekUtil().get(0), ReportUtil.weekUtil().get(1), param, enterpriseId, costCenter));
                hm.put("totalSum", baseMapper.costCenterBodyCountTotal(enterpriseId));

            } else if (type.equals("2")) { // 月
                list.addAll(baseMapper.costCenterBodyCount(ReportUtil.dateUtil().get(0), ReportUtil.dateUtil().get(1), param, enterpriseId, costCenter));
                hm.put("totalSum", baseMapper.costCenterBodyCountTotal(enterpriseId));

            }

        }
        if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)) {
            LocalDateTime start = LocalDateTimeUtils.convertStringToLDT(startTime, "yyyy-MM-dd HH:mm:ss");
            LocalDateTime end = LocalDateTimeUtils.convertStringToLDT(endTime, "yyyy-MM-dd HH:mm:ss");

            list.addAll(baseMapper.costCenterBodyCount(start, end, param, enterpriseId, costCenter));
            hm.put("totalSum", baseMapper.costCenterBodyCountTotal(enterpriseId));

        }
        hm.put("data", list);
        return JsonResult.success("查询成功", hm);
    }

    @Override
    public UserVO getUserInfoByUserName(String userName) {
        return baseMapper.getUserInfoByUserName(userName);
    }

    /**
     * 插入用户信息
     *
     * @param read
     */
    @Override
    @Transactional
    public void importExcelUser(List<UserInfoExcelIn> read, String companyNameInfo) {
        //1. 拿到部门的map
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(Role::getId, Role::getName, Role::getIsProduce, Role::getParentId);
        // 查询出所有信息
        List<Role> role = roleService.list(queryWrapper);
        //选出所有的一级部门
        Map<String, Long> roleMap = role.stream()
                .filter(info -> info.getIsProduce() && info.getParentId() == -1L)
                .collect(Collectors.toMap(Role::getName, Role::getId));

        //拿到所有的岗位
        Map<String, Long> collectPost = role.stream()
                .filter(info -> !info.getIsProduce())
                .collect(Collectors.toMap(Role::getName, Role::getId));

        for (UserInfoExcelIn userInfoExcelIn : read) {
            User user = new User();
            user.setAccount(userInfoExcelIn.getUserCode());
            user.setSex(userInfoExcelIn.getSex().equals("男") ? 1 : 0);
            user.setStatus(1);
            user.setCreateTime(LocalDateTime.now());
            user.setCreatorName("admin|admin");
            user.setUpdateTime(LocalDateTime.now());
            user.setVersion(0L);
            user.setIsDeleted(false);
            user.setUsername(userInfoExcelIn.getUserCode());
            user.setNickname(userInfoExcelIn.getUserName());
            user.setDepartmentId(roleMap.get(userInfoExcelIn.getDepartmentName()) == null ? null : roleMap.get(userInfoExcelIn.getDepartmentName()));
            user.setPostId(collectPost.get(userInfoExcelIn.getPostName()) == null ? null : collectPost.get(userInfoExcelIn.getPostName()));
            user.setCompanyInfoId(Long.valueOf(companyNameInfo));
            user.setPhone(userInfoExcelIn.getUserPhone());
            user.setPasswordRsa("gBs1ZCKZ9KChnKI2DE1z11BaYa5P6+U2+xn1+Jeo8f0kn6bs3tveoHaOqKld62X1owO//8zSLaLQqFHfYlMPHF92+awt1PDqPuxKDWzDy/1H5eFv0Vb1YodsEijAqlRyhsFfot7rn8dcVwD1WSB490EP8GgY5HYDrMTP+DDrmXk=");
            user.setPassword("$2a$10$xGR6Q.ipkqd/d4j307JqOukI1eJkEXoXfXPUhiXtMPRpI6B5z/Q6q");
            this.save(user);

            UserRole userRole = UserRole.builder().
                    userId(user.getId()).
                    roleId(user.getPostId()).
                    createTime(LocalDateTime.now()).
                    creatorName("admin|admin").
                    modifierName(LocalDateTime.now()).
                    build();
            userRoleService.save(userRole);
        }
    }

    @Autowired
    SystemDingTalkInfoDao systemDingTalkInfoDao;

    @Autowired
    RoleDao roleDao;

    @Override
    public void syncDingUserToSysUer() throws Exception {
        // 同步钉钉用户数据 根据部门
        // 同时同步对应部门下面用户的岗位 到部门表
        SystemDingTalkInfo systemDingTalkInfo = systemDingTalkInfoDao.selDingTalkInfo();
        if (systemDingTalkInfo != null) {
            String accessToken = DingDingUtils.getAccessTokenByKeySecret(systemDingTalkInfo.getClientId(), systemDingTalkInfo.getClientSecret());
            List<Role> dingDepartData = roleDao.getDingDepartData();
            for (Role dingDepartDatum : dingDepartData) {
                processAllPages(accessToken, dingDepartDatum.getDingDepartmentId());
            }
        }
    }

    @Override
    public SystemDingTalkInfo getUserDingConfigInfo() {
        return systemDingTalkInfoDao.selDingTalkInfo();
    }

    @Override
    public List<User> selUserDingInfo() {
        return baseMapper.selUserDingInfo();
    }

    private void processAllPages(String accessToken, Long dingDepartmentId) throws Exception {
        int offset = 0;
        int pageSize = 10; // 假设每页大小为1，根据实际情况调整
        boolean hasMore = true;

        while (hasMore) {
            String departUserList = DingDingUtils.getDeptUserDetailListInfo(accessToken, dingDepartmentId, offset, pageSize);
            hasMore = processJsonResponse(departUserList, dingDepartmentId);
            if (hasMore) {
                offset += pageSize; // 更新offset以获取下一页数据
            }
        }
    }

    public boolean processJsonResponse(String jsonResponse, Long dingDepartmentId) {
        // 使用FastJSON将JSON字符串解析为JSONObject
        com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(jsonResponse);

        // 检查是否有错误发生
        if (jsonObject.getIntValue("errcode") != 0) {
            log.error("Error: " + jsonObject.getString("errmsg"));
            return false;
        }

        // 获取结果对象
        com.alibaba.fastjson.JSONObject resultObject = jsonObject.getJSONObject("result");

        // 获取has_more字段的值
        boolean hasMore = resultObject.getBoolean("has_more");
        log.info("是否还有更多的数据: " + (hasMore ? "是" : "否"));

        // 如果有更多数据，获取next_cursor值
        if (hasMore) {
            int nextCursor = resultObject.getIntValue("next_cursor");
            log.info("下一个分页的游标: " + nextCursor);
        }

        // 获取list数组
        com.alibaba.fastjson.JSONArray listArray = resultObject.getJSONArray("list");
        Role role3 = roleDao.getRoleDepartData(null, dingDepartmentId);

        for (int i = 0; i < listArray.size(); i++) {
            com.alibaba.fastjson.JSONObject userObject = listArray.getJSONObject(i);
            String name = userObject.getString("name");
            String userId = userObject.getString("userid");
            String mobile = userObject.getString("mobile");
            String username = userObject.getString("mobile"); // 注意：这里可能需要根据实际API返回字段调整
            String email = userObject.getString("email"); // 注意：这里可能需要根据实际API返回字段调整

            User user = new User();
            user.setNickname(name);
            user.setSex(1);

            //岗位
            user.setPostId(role3.getId());
            user.setRoleIds(role3.getId().toString());

            user.setUsername(username);
            user.setPhone(mobile);
            user.setEmail(email);

            Role role2 = roleDao.getRoleDepartData(null, role3.getDingParentId());
            //上级部门
            user.setDepartmentId(role2.getId());

            user.setDingDepartmentId(dingDepartmentId);
            user.setDingUserId(userId);

            if (baseMapper.isExist(user.getUsername()) > 0) {
                QueryWrapper<User> qw = new QueryWrapper<>();
                qw.eq("phone", user.getPhone());
                qw.eq("username", user.getUsername());
          /*      qw.eq("nickname", user.getNickname());*/
                User oldUser = baseMapper.selectOne(qw);
                user.setId(oldUser.getId());
                this.update(user, user.getRoleIds().split(","));
            } else {
                this.addUser(user, user.getRoleIds().split(","));
            }

        }

        return hasMore;
    }


}
